#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "comm.h"
#include <cstring>
#include <unistd.h>
bool Makefifo()
{
    int n = mkfifo(FILENAME, 0666);
    if (n < 0)
    {
        std::cerr << "errno" << errno << " ,errstring" << strerror(errno) << std::endl;
        return false;
    }
    std::cout << "mkfifo success... read" << std::endl;
    return true;
}

int main()
{
Start:
    // 1.首先打开管道文件，打开不成功说明管道文件还没创建出来
    int rid = open(FILENAME, O_RDONLY);
    if (rid < 0)
    {
        std::cerr << "errno" << errno << " ,errstring" << strerror(errno) << std::endl;
        // 创建管道
        if (Makefifo())
            goto Start;
        else
            return 1;
    }
      std::cout << "open fifo success..." << std::endl;


    char buffer[1024];
    // 2.读取工作
    while (true)
    {
        int n = read(rid, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "Client say# " << buffer << std::endl;
        }
        // 根据管道的四种情况，如果写端关闭，读端一直读，会读到0
        else if (n == 0)
        {
            std::cout << "client quit, server quit too!" << std::endl;
            break;
        }
        else
        {
            std::cerr << "errno" << errno << " ,errstring" << strerror(errno) << std::endl;
        }
    }

    //关闭文件
    close(rid);
    std::cout << "close fifo success..." << std::endl;

    return 0;
}